import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, getProfile, type LoginParams, type AdminInfo } from '@/api/admin'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态定义
  const token = ref<string>('')
  const userInfo = ref<AdminInfo | null>(null)
  const isLoading = ref<boolean>(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const isSuperAdmin = computed(() => userInfo.value?.is_super_admin === 1)

  /**
   * 初始化用户状态（从localStorage恢复）
   */
  function initUserState() {
    const savedToken = localStorage.getItem('admin_token')
    const savedUserInfo = localStorage.getItem('admin_userInfo')
    
    if (savedToken) {
      token.value = savedToken
    }
    
    if (savedUserInfo) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        // 清除无效数据
        localStorage.removeItem('admin_userInfo')
      }
    }
  }

  /**
   * 登录操作
   * @param loginParams 登录参数
   */
  async function login(loginParams: LoginParams): Promise<boolean> {
    try {
      isLoading.value = true
      
      const response = await apiLogin(loginParams)
      
      if (response.success) {
        // 保存token和用户信息
        token.value = response.data.token
        userInfo.value = response.data.userInfo
        
        // 持久化到localStorage
        localStorage.setItem('admin_token', response.data.token)
        localStorage.setItem('admin_userInfo', JSON.stringify(response.data.userInfo))
        
        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error(response.message || '登录失败')
        return false
      }
    } catch (error: any) {
      console.error('登录错误:', error)
      ElMessage.error(error.message || '登录失败，请稍后重试')
      return false
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取用户信息
   */
  async function fetchUserInfo(): Promise<boolean> {
    try {
      if (!token.value) {
        return false
      }
      
      const response = await getProfile()
      
      if (response.success) {
        userInfo.value = response.data
        // 更新localStorage中的用户信息
        localStorage.setItem('admin_userInfo', JSON.stringify(response.data))
        return true
      } else {
        return false
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return false
    }
  }

  /**
   * 登出操作
   */
  function logout() {
    // 清除状态
    token.value = ''
    userInfo.value = null
    
    // 清除localStorage
    localStorage.removeItem('admin_token')
    localStorage.removeItem('admin_userInfo')
    
    ElMessage.success('已退出登录')
  }

  /**
   * 重置状态
   */
  function resetState() {
    token.value = ''
    userInfo.value = null
    isLoading.value = false
  }

  // 初始化状态
  initUserState()

  return {
    // 状态
    token,
    userInfo,
    isLoading,
    
    // 计算属性
    isLoggedIn,
    isSuperAdmin,
    
    // 方法
    login,
    logout,
    fetchUserInfo,
    resetState,
    initUserState
  }
})
